package com.ehotting.edsta.gateway.filter;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

import com.ehotting.eaf.core.exception.CaptchaException;
import com.ehotting.eaf.core.utils.AssertUtils;
import com.ehotting.eaf.core.utils.ServletUtils;
import com.ehotting.eaf.core.utils.StringUtils;
import com.ehotting.edsta.gateway.config.properties.CaptchaProperties;
import com.ehotting.edsta.gateway.service.ValidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import reactor.core.publisher.Flux;

/**
 * 验证码过滤器
 * 
 * @author edsta
 */
@Slf4j
@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
{
    private final static String[] VALIDATE_URL = new String[] {
            "/auth/login",
            "/auth/register",
            "/auth/userSms/getSmsCode",
            "/auth/userSms/sendSmsCode4Reset"};

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private CaptchaProperties captchaProperties;

    private static final String CODE = "code";

    private static final String UUID = "uuid";

    @Override
    public GatewayFilter apply(Object config)
    {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            log.info("request.getURI().getPath():{}",request.getURI().getPath());
            // 非登录/注册请求或验证码关闭，不处理
            if (!StringUtils.containsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL) || !captchaProperties.getEnabled())
            {
                return chain.filter(exchange);
            }
            log.info("start validate img code>>>>");
            try
            {
                String rspStr = resolveBodyFromRequest(request);
                AssertUtils.notNull(rspStr,new CaptchaException("验证码信息为空"));
                JSONObject obj = JSONObject.parseObject(rspStr);
                String code = obj.getString(CODE);
                String uuid = obj.getString(UUID);
                log.info("code:{},uuid:{}",code,uuid);
                validateCodeService.checkCapcha(code, uuid);
            }
            catch (Exception e)
            {
                log.error("exception:",e);
                String msg  = "";
                if(e instanceof  CaptchaException){
                    msg = e.getMessage();
                }else{
                    msg = (e.getMessage()==null?"内部系统异常":e.getMessage());
                }
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg);
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest)
    {
        log.info("Start resolveBodyFromRequest.");
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        log.info("finish resolveBodyFromRequest.");
        return bodyRef.get();
    }
}
